package com.atguigu.gmall.mq.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@RabbitListener(queues = "queue1")
@Component
public class Consumer {

    //接收消息 手动应答
    @RabbitHandler
    public void receiveMessage(String msg, Message message, Channel channel) {

        try {
            System.out.println(msg);
            int i = 1/0;
            //应答成功接收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //e.printStackTrace();
            //当前此消息是否为重新发送的消息
            if (message.getMessageProperties().isRedelivered()) {
                //第二次 再次投递的消息
                System.out.println("当前为第二次投递");
                try {
                    channel.basicReject(message.
                            getMessageProperties().getDeliveryTag(), false);
                    //丢弃，记录日志  人为干预
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                //是第一次 投递
                System.out.println("当前为第一次投递");
                try {
                    //否定确认
                    //requeue：是否放回队列（再给一次机会
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                            false, true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        //应答成功
    }

}
